package com.lolan.training.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
public class IOUtils {
	private static final ObjectMapper MAPPER = new ObjectMapper();
	private static final TypeReference<Object> typeRef
			= new TypeReference<Object>() {};
	public static String readAsString(String filePath){
		StringBuilder sb = new StringBuilder();
		try {
			File file = new File(filePath);
			// 创建一个 FileReader 对象，用来读取文件的字符流
			FileReader fr = new FileReader(file);
			// 创建一个 BufferedReader 对象，用来缓冲字符流，并提供按行读取的方法
			BufferedReader br = new BufferedReader(fr);
			// 定义一个变量，用来存储每行的内容
			String line;
			// 循环读取每一行，直到文件结束
			while ((line = br.readLine()) != null) {
				// 将每行的内容追加到 StringBuilder 中，并添加换行符
				sb.append(line).append("\n");
			}
			// 关闭 BufferedReader 和 FileReader
			br.close();
			fr.close();
		} catch (
				IOException e) {
			// 处理异常
			e.printStackTrace();
		}
		return sb.toString();
	}
	public static Object jsonToObject(String jsonString){
		/*
		* 类似python的json.loads
		* */
		Object objectMap = null;
		try {
			if (jsonString !=null)
				objectMap = MAPPER.readValue(jsonString, typeRef);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
		return objectMap;
	}
	public static Object fileToObject(String filePath){
		/*
		 * 类似python的json.load
		 * */
		Object objectMap = null;
		try {
			if (filePath != null) {
				File f = new File(filePath);
				objectMap = MAPPER.readValue(f, typeRef);
			}
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return objectMap;
	}
	public static String objectToJson(Object objectMap){
		/*
		 * 类似python的json.dumps
		 * */
		String jsonString = "";
		try {
			 jsonString = MAPPER.writeValueAsString(objectMap);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
		return jsonString;
	}
}
